use std::fs;
use std::path::PathBuf;
use tauri::tray::{TrayIconBuilder, TrayIconEvent};
use tauri::Manager;

// 获取数据目录路径
fn get_data_dir(app: &tauri::AppHandle) -> PathBuf {
    app.path().app_data_dir().unwrap()
}

// 加载待办事项
#[tauri::command]
fn load_todos(app: tauri::AppHandle) -> Result<String, String> {
    let data_dir = get_data_dir(&app);
    let todos_path = data_dir.join("todos.json");

    if !data_dir.exists() {
        fs::create_dir_all(&data_dir).map_err(|e| e.to_string())?;
    }

    if todos_path.exists() {
        fs::read_to_string(todos_path).map_err(|e| e.to_string())
    } else {
        Ok("[]".to_string())
    }
}

// 保存待办事项
#[tauri::command]
fn save_todos(app: tauri::AppHandle, data: String) -> Result<(), String> {
    let data_dir = get_data_dir(&app);
    let todos_path = data_dir.join("todos.json");

    if !data_dir.exists() {
        fs::create_dir_all(&data_dir).map_err(|e| e.to_string())?;
    }

    fs::write(todos_path, data).map_err(|e| e.to_string())
}

// 加载设置
#[tauri::command]
fn load_settings(app: tauri::AppHandle) -> Result<String, String> {
    let data_dir = get_data_dir(&app);
    let settings_path = data_dir.join("settings.json");

    if !data_dir.exists() {
        fs::create_dir_all(&data_dir).map_err(|e| e.to_string())?;
    }

    if settings_path.exists() {
        fs::read_to_string(settings_path).map_err(|e| e.to_string())
    } else {
        Ok(r#"{"theme":"system","opacity":0.95}"#.to_string())
    }
}

// 保存设置
#[tauri::command]
fn save_settings(app: tauri::AppHandle, data: String) -> Result<(), String> {
    let data_dir = get_data_dir(&app);
    let settings_path = data_dir.join("settings.json");

    if !data_dir.exists() {
        fs::create_dir_all(&data_dir).map_err(|e| e.to_string())?;
    }

    fs::write(settings_path, data).map_err(|e| e.to_string())
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![
            load_todos,
            save_todos,
            load_settings,
            save_settings
        ])
        .setup(|app| {
            // 加载托盘图标
            let tray_icon = match app
                .path()
                .resolve("icons/tray-icon.png", tauri::path::BaseDirectory::Resource)
            {
                Ok(icon_path) => match std::fs::read(&icon_path) {
                    Ok(icon_bytes) => match image::load_from_memory(&icon_bytes) {
                        Ok(img) => {
                            let rgba = img.to_rgba8();
                            let (width, height) = rgba.dimensions();
                            tauri::image::Image::new_owned(rgba.into_raw(), width, height)
                        }
                        Err(_) => app.default_window_icon().unwrap().clone(),
                    },
                    Err(_) => app.default_window_icon().unwrap().clone(),
                },
                Err(_) => app.default_window_icon().unwrap().clone(),
            };

            // 创建系统托盘图标（不显示菜单）
            let tray = TrayIconBuilder::new()
                .icon(tray_icon)
                .on_tray_icon_event(|tray, event| {
                    // 任何点击事件都切换回主窗口
                    if let TrayIconEvent::Click { .. } | TrayIconEvent::DoubleClick { .. } = event {
                        let app = tray.app_handle();
                        // 隐藏悬浮窗口
                        if let Some(floating_window) = app.get_webview_window("floating") {
                            let _ = floating_window.hide();
                        }
                        // 显示主窗口
                        if let Some(main_window) = app.get_webview_window("main") {
                            let _ = main_window.show();
                            let _ = main_window.set_focus();
                        }
                    }
                })
                .build(app)?;

            // 监听主窗口关闭事件，阻止退出并隐藏窗口
            if let Some(main_window) = app.get_webview_window("main") {
                let window_clone = main_window.clone();
                main_window.on_window_event(move |event| {
                    if let tauri::WindowEvent::CloseRequested { api, .. } = event {
                        api.prevent_close();
                        let _ = window_clone.hide();
                    }
                });
            }

            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
